package com.ysx.aspect;


import com.ysx.RoleUtil;
import com.ysx.annotation.Authentication;
import com.ysx.student.bean.StudentBean;
import com.ysx.teacher.bean.TeacherBean;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class AuthenticationAspect {

    @Pointcut(value = "@annotation(com.ysx.annotation.Authentication)")
    public void xx(){}


    /**
     * joinPoint
     */
    @Around("xx()")
    public Object check(ProceedingJoinPoint pjp){

        Object object = null;
        Integer id = 0;
        try {

            //  这几行代码不要记 目标是拿到方法上的注解
            Signature signature = pjp.getSignature();
            Object[] args = pjp.getArgs();
            Object bean =args[0];
            if(bean instanceof StudentBean){
                StudentBean studentBean =(StudentBean)bean;
                id=studentBean.getId();
            }else if(bean instanceof TeacherBean){
                TeacherBean teacherBean =(TeacherBean)bean;
                id=teacherBean.getId();
            }
            MethodSignature methodSignature = (MethodSignature)signature;
            Method method = methodSignature.getMethod();
            Authentication annotation = method.getAnnotation(Authentication.class);

            boolean check  = annotation.check();

            if(check == true){
                //要做权限检验
                //String roleName="学生";

                String roleName = RoleUtil.getRoleName(id);
                if("系统管理员".equals(roleName) || "老师".equals(roleName) ){
                    System.out.println("权限检验通过...");
                    // 执行方法
                    System.out.println("进入业务方法....");
                    object =pjp.proceed();
                    System.out.println("结束业务方法....");
                }else{
                    System.out.println("权限检验没有通过 请联系系统管理员");
                    //后面的代码不要继续执行  return
                    return null;
                }
            }

        } catch (Throwable e) {
            System.out.println(e);
        }
        return object;

    }



}
